/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {Form, Popconfirm, Table, Tabs} from 'antd';

import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import DescGroup from "../../../components/DescriptionGroup";
import ViewTitle from "../../../components/ViewTitle";
import styles from "../../index.less";
import {ModalView} from "antd-extra";
import ModalCreateOutboundLot from "./ModalCreateOunboundLot";
import ModalOutboundLotDetail from "./ModalOutboundLotDetail";
import _ from "lodash";
import ProductionElement from "../../../components/ProductionElement";

const {TabPane} = Tabs;
moment.locale('zh-cn');
const table = 'OutboundOrder';
@Form.create()
@connect(({user, global, dynamicLabel, sales, store}) => ({...user, ...store, ...sales, ...dynamicLabel, ...global}))
export default class ModalOutboundOrderDetail extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    this.props.dispatch({
      type: 'global/getModel',
      payload: {table}
    });
    this.props.dispatch({
      type: 'global/getModel',
      payload: {table: 'OutboundLot'}
    });
    this.onDataLoad().then(response => {
      this.setState(response);
    });
  }

  async onDataLoad() {
    const {values, dispatch} = this.props;
    const {code} = values;

    const orderRes = await dispatch({
      type: 'store/findOutboundOrder',
      payload: {orderCode: code}
    });
    const lotRes = await dispatch({
      type: 'store/findOutboundLots',
      payload: {orderCode: code}
    });

    return {lots: lotRes.result, outboundOrder: orderRes.result};
  }

  onOutboundLotDetail = values => {
    ModalView.open(ModalOutboundLotDetail, {
      title: '出货记录详情',
      width: '920px',
      maskClosable: false
    }, {
      values,
      callback: (result) => {
        const {lotCode} = values;
        const {shippingFee = 0} = result;

        this.props.dispatch({
          type: 'store/updateShippingFee',
          payload: {shippingFee, lotCode}
        }).then(response => {
          this.requestReturn(response);
          this.componentDidMount();
        });
      }
    });
  };

  //采购单中需要在出货单中显示的字段
  showKeys = ['projectType', 'division', 'customer', 'address', 'contacts', 'contactsPhone', 'prodName', 'prodCode', 'count', 'label', 'package', 'packageWay', 'deliverWay', 'deliverRequire', 'outboundCount'];

  lotCols() {
    const temp = this.getOutboundLotCols();
    temp.push(
      {
        title: '操作', key: 'opt', dataIndex: "opt", render: (value, record) => {
          return <span>
                          {<a style={{marginRight: '6px'}}
                              onClick={() => this.onOutboundLotDetail(record)}>详情</a>}
            {<Popconfirm
              title="确认删除"
              onConfirm={() => {
                this.props.dispatch({
                  type: 'store/deleteOutboundLot',
                  payload: {...record}
                }).then(res => {
                  this.componentDidMount();
                });
              }}
              okText="是"
              cancelText="否"
            >
              <a style={{marginRight: '6px'}}>删除</a>
            </Popconfirm>}
            </span>;
        }
      }
    );
    return temp;
  }

  prodTableCol() {
    const model = this.props['OutboundOrderModel'];

    const {prods} = model;
    const temp = [];
    _.map(prods, (item, key) => {
      const {_type, title, enableArea} = item;

      if (_.includes(enableArea, "table")) {
        const it = _type === 'date' ? {
          title, key, dataIndex: key, render: value => {
            return <div>{moment(value).format('YYYY-MM-DD')}</div>;
          }
        } : {title, key, dataIndex: key};
        temp.push(it);
      }
    });

    temp.push(
      {
        title: "操作", key: 'opt', dataIndex: "opt", render: (value, record) => {
          return <a style={{marginRight: '6px'}} onClick={() => {
            const {values} = this.props;
            const {code} = values;

            ModalView.open(ModalCreateOutboundLot, {
              title: '创建出货记录',
              width: '1080px'
            }, {
              record,
              callback: payload => {
                payload.orderCode = code;
                payload._code = record._code;
                payload.division = this.props.values.division;
                this.props.dispatch({
                  type: 'store/createOutboundLot',
                  payload
                }).then(res => {
                  this.requestReturn(res);
                  this.componentDidMount();
                });
              }
            });
          }}>出货</a>;
        }
      }
    );
    return temp;
  }

  materialCols = [
    {
      title: '商品', dataIndex: 'prodName', render: (value, record) => {
        const {prodName, prodCode} = record;
        return <ProductionElement name={prodName} code={prodCode}></ProductionElement>;
      }
    },
    {
      title: '物料', dataIndex: 'material', render: (value, record) => {
        const {name, code} = record;
        return <ProductionElement name={name} code={code}></ProductionElement>;
      }
    },
    {title: '物料编号', dataIndex: 'number'},
    {title: '物料类型', dataIndex: 'type'},
    {title: '物料规格', dataIndex: 'spec'},
    {title: '物料含量', dataIndex: 'materialContent',render: (value, record) => {
      return <div>{value+"%"}</div>;
      }},
    {title: '物料供应商', dataIndex: 'vendor'}
  ];

  render() {
    const {style, cols = 3, values} = this.props;
    const model = this.props[`${table}Model`];

    if (!model) return;
    const {lots, outboundOrder = {}} = this.state;

    const {prods} = outboundOrder;
    let allOutboundCount = 0;
    const _materials = [];
    _.map(prods, item => {
      const {_code,materials=[],prodName,prodCode} = item;
      const temp = _.filter(lots, it => it.code === _code);

      let _Count = 0;
      if (temp) {
        _.map(temp, lot => {
          const {outboundCount} = lot;
          _Count += outboundCount;
          allOutboundCount += outboundCount;
        });
      }
      item.outboundCount = _Count;

      _.map(materials, material => {
        material.prodName=prodName;
        material.prodCode=prodCode;
        _materials.push(material);
      })

    });

    outboundOrder.outboundCount = allOutboundCount;
    const _labels = _.filter(model, (item, key) => {
      if (key !== 'labels' && _.includes(item.enableArea, 'detail')) {
        item.key = key;
        return item;
      }
    });
    _.map(_labels, item => {
      const {_type, key} = item;
      if (_type.toLowerCase() === 'switch') {
        outboundOrder[key] = outboundOrder[key] ? "是" : "否";
      }
      if (_type.toLowerCase() === 'date') {
        outboundOrder[key] = outboundOrder[key] ? moment(outboundOrder[key]).format('YYYY-MM-DD') : '';
      }
    });



    return (
      <div style={{...style}}>
        <Tabs defaultActiveKey="1">
          <TabPane tab="订单" key="1">
            <ViewTitle
              title={'订单信息'}
              level={1}

            ></ViewTitle>
            <DescGroup
              {...{

                labels: _labels,
                values: outboundOrder,
                size: 'small',
                column: cols
              }}
            ></DescGroup>
            <ViewTitle
              title={'商品信息'}
            ></ViewTitle>
            <Table
              className={styles.antTable}
              bordered={true}
              columns={this.prodTableCol()}
              dataSource={prods}
              scroll={{x: true}}
              pagination={true}
            ></Table>
            <ViewTitle
              title={'物料信息'}
            ></ViewTitle>
            <Table
              className={styles.antTable}
              bordered={true}
              columns={this.materialCols}
              dataSource={_materials}
              scroll={{x: true}}
              pagination={true}
            ></Table>
          </TabPane>
          <TabPane tab="出货记录" key="2">
            <ViewTitle
              title={'出货记录列表'}
            ></ViewTitle>
            <Table
              className={styles.antTable}
              bordered={true}
              columns={this.lotCols()}
              dataSource={lots}
              scroll={{x: true}}
              pagination={true}
            ></Table>
          </TabPane>
        </Tabs>


      </div>

    );
  }
}

